﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;

namespace Bierdopje.API
{
    public class ApiCache
    {
        private List<ApiCacheItem> m_ApiCacheItems;

        public ApiCache()
        {
            string location = GetCacheFileName();
            if (File.Exists(location))
            {
                TextReader _TR = new StreamReader(location);
                XmlSerializer _XS = new XmlSerializer(typeof(List<ApiCacheItem>));
                m_ApiCacheItems = (List<ApiCacheItem>)_XS.Deserialize(_TR);
                _TR.Close();
            }
            else
            {
                m_ApiCacheItems = new List<ApiCacheItem>();
                this.Save();
            }
        }

        public string GetItemFromCache(string url)
        {
            var cacheItems = (from cacheItem in m_ApiCacheItems
                              where
                                cacheItem.Url == url
                              select cacheItem).FirstOrDefault();


            if (cacheItems != null)
                return cacheItems.Response;
            else
                return "";
        }

        public void StoreItemInCache(string url, string response)
        {
            var cacheItems = (from cacheItem in m_ApiCacheItems
                              where
                                cacheItem.Url == url
                              select cacheItem).FirstOrDefault();


            if (cacheItems != null)
                m_ApiCacheItems.Remove(cacheItems);

            m_ApiCacheItems.Add(new ApiCacheItem() { Url = url, Response = response });

            this.Save();
        }

        public static string GetCacheFileName()
        {
            string configFileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "bierdopje_api.cache");
            return configFileName;
        }

        private void Save()
        {
            TextWriter _TW = new StreamWriter(GetCacheFileName(), false);
            XmlSerializer _XS = new XmlSerializer(typeof(List<ApiCacheItem>));
            _XS.Serialize(_TW, m_ApiCacheItems);
            _TW.Close();
        }

        
    }

    public class ApiCacheItem
    {
        public ApiCacheItem()
        {
            Age = DateTime.Now;
        }

        public string Url;
        public string Response;
        public DateTime Age;
    }
}
